import React, { useState } from "react";
import { Button } from "antd";
import { flushSync } from "react-dom";
import "./Vote.less";

/**
 * 执行一次useState：把需要的状态信息都放在对象中统一管理
 *      + 执行setState方法的时候，传递的是什么值，就把状态整体改为什么值
 *      ==> 把状态值修改为 {supNum : 11} ,oppNum 成员就丢失了
 *      ==> 不支持部分状态更新
 *
 * 官方的建议是：需要多个状态，就把useState执行多次即可
 */

const Vote = function Vote(props) {
  // 执行一次useState，一个对象统一管理
  //   let [state, setState] = useState({ supNum: 10, oppNum: 5 });
  //   const handle = function (type) {
  //     if (type == "upp") {
  //       setState({
  //         ...state,
  //         supNum: state.supNum + 1,
  //       });
  //     }
  //     if (type == "opp") {
  //       setState({
  //         ...state,
  //         oppNum: state.oppNum + 1,
  //       });
  //     }
  //   };

  //   官方建议，多个状态，就多次执行useState
  let [supNum, setSupNum] = useState(10),
    [oppNum, setOppNum] = useState(5);

  console.log("渲染");
  const handle = (type) => {
    if (type === "upp") {
      setSupNum(supNum + 1);
      flushSync(() => {
        setSupNum(supNum + 1);
      });
      setSupNum(supNum + 1);
      return;
    }
    setOppNum(oppNum + 1);
  };

  return (
    <div className="vote-box">
      <div className="header">
        <h2 className="title">{props.title}</h2>
        <span className="num">{oppNum + supNum}</span>
      </div>

      <div className="main">
        <p>支持人数：{supNum}人</p>
        <p>反对人数：{oppNum}人</p>
      </div>

      <div className="footer">
        <Button
          type="primary"
          size="small"
          className="btn1"
          onClick={handle.bind(null, "upp")}
        >
          新增
        </Button>
        <Button
          type="primary"
          danger
          className="btn2"
          onClick={handle.bind(null, "opp")}
        >
          反对
        </Button>
      </div>
    </div>
  );
};

export default Vote;
